// src/pages/GradedDoctor/ScheduleManagement.jsx
import React, { useEffect, useState } from 'react';
import { Button, Avatar, Spin, message } from 'antd';
import styled from 'styled-components';
import { useDispatch, useSelector } from 'react-redux';
import { fetchSchedule, updateSchedule, selectSchedule, selectScheduleLoading, selectScheduleError } from '../../../slices/scheduleSlice';
import { selectUserInfo } from '../../../slices/userSlice';
import dayjs from 'dayjs';

const ScheduleContainer = styled.div`
  padding: 24px;
  background: #fff;
  min-height: calc(100vh - 64px);
`;

const DoctorInfoSection = styled.div`
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px;
  background: #fafafa;
  border-radius: 4px;
  
  .avatar {
    width: 80px;
    height: 80px;
    margin-right: 16px;
  }
  
  .info {
    font-size: 14px;
    color: #333;
  }
`;

const ScheduleGrid = styled.div`
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 8px;
  margin-bottom: 24px;
`;

const DayCell = styled.div`
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
  background: #fafafa;
`;

const DayHeader = styled.div`
  padding: 8px;
  text-align: center;
  background: ${({ $isOdd }) => ($isOdd ? '#52c41a' : '#1890ff')};
  color: #fff;
  font-weight: 500;
`;

const TimeSlot = styled.div`
  padding: 8px;
  text-align: center;
  background: ${({ $active, $isOdd }) =>
    $active ? ($isOdd ? '#52c41a' : '#1890ff') : ($isOdd ? '#f6ffed' : '#e6f7ff')};
  color: ${({ $active }) => ($active ? '#fff' : '#333')};
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    background: ${({ $active, $isOdd }) =>
      $active ? ($isOdd ? '#389e0d' : '#096dd9') : ($isOdd ? '#b7eb8f' : '#91d5ff')};
    color: #fff;
  }
`;

const ButtonContainer = styled.div`
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
`;

const ScheduleManagement = () => {
  const dispatch = useDispatch();
  const scheduleData = useSelector(selectSchedule); // 排班数据
  const loading = useSelector(selectScheduleLoading); // 加载状态
  const error = useSelector(selectScheduleError); // 错误信息
  const userInfo = useSelector(selectUserInfo); // 用户信息
  
  const [editableSchedule, setEditableSchedule] = useState([]); // 可编辑的排班数据
  const [messageApi, contextHolder] = message.useMessage(); // 正确使用 useMessage

  // 辅助函数：获取头像图片路径
  const getAvatarSrc = (head) => {
    if (!head) return '/images/default-avatar.png'; // 使用绝对路径
    if (head.startsWith('http://') || head.startsWith('https://')) {
      return head; // 直接使用完整的URL
    }
    return `/images/headers/${head}`; // 使用相对路径，通过代理转发
  };

  useEffect(() => {
    if (userInfo && userInfo.id) {
      dispatch(fetchSchedule(userInfo.id));
    }
  }, [dispatch, userInfo]);
  
  // 监听错误状态，显示错误提示
  useEffect(() => {
    if (error) {
      messageApi.error(error);
    }
  }, [error, messageApi]);

  // 当排班数据更新时，初始化可编辑的排班数据
  useEffect(() => {
    if (scheduleData && scheduleData.length > 0) {
      setEditableSchedule(scheduleData.map(item => ({
        date: item.date,
        morning: item.morning || 0,
        afternoon: item.afternoon || 0,
        night: item.night || 0,
      })));
    } else {
      setEditableSchedule([]);
    }
  }, [scheduleData]);

  // 处理时间段点击事件，切换班次状态
  const handleTimeSlotClick = (dayIndex, timePeriod) => {
    if (dayIndex < 0 || dayIndex >= editableSchedule.length) {
      messageApi.error('排班数据索引超出范围');
      return;
    }

    const newSchedule = [...editableSchedule];
    if (timePeriod === 'morning') {
      newSchedule[dayIndex].morning = newSchedule[dayIndex].morning === 0 ? 1 : 0;
    } else if (timePeriod === 'afternoon') {
      newSchedule[dayIndex].afternoon = newSchedule[dayIndex].afternoon === 0 ? 1 : 0;
    } else if (timePeriod === 'night') {
      newSchedule[dayIndex].night = newSchedule[dayIndex].night === 0 ? 1 : 0;
    }
    setEditableSchedule(newSchedule);
  };

  // 辅助函数：转义字符串以避免 SQL 语法错误
  const escapeForSQL = (str) => {
    return str.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/'/g, "\\'");
  };

  // 处理确认修改排班
  const handleSubmit = async () => {
    if (!editableSchedule || editableSchedule.length === 0) {
      messageApi.warning('排班数据为空，请检查后再提交。');
      return;
    }
    
    // 构建 newdate 数组
    const newdate = editableSchedule.map(item => ({
      date: item.date,
      morning: item.morning,
      afternoon: item.afternoon,
      night: item.night,
    }));
    
    // 转换为 JSON 字符串并转义双引号
    const newdateStr = JSON.stringify(newdate).replace(/"/g, '\\"');
    
    const payload = {
      id: userInfo.id,
      newdate: newdateStr, // 发送转义后的字符串
    };
    
    console.log('发送修改排班请求:', payload);
    
    try {
      const res = await dispatch(updateSchedule(payload)).unwrap();
      if (res.code === 1) {
        messageApi.success('排班信息修改成功');
        // 重新获取排班数据
        dispatch(fetchSchedule(userInfo.id));
      } else {
        messageApi.error(res.msg || '修改排班失败');
      }
    } catch (err) {
      console.error('修改排班失败:', err);
      messageApi.error('修改排班失败');
    }
  };


  // 生成日历数据
  const generateCalendarData = () => {
    const days = [];
    const currentDate = dayjs();
    const year = currentDate.year();
    const month = currentDate.month(); //0-11
    const daysInMonth = currentDate.daysInMonth();
    
    for (let i = 1; i <= daysInMonth; i++) {
      const dateObj = dayjs(new Date(year, month, i));
      const weekday = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][dateObj.day()];
      const dateStr = dateObj.format('YYYY-MM-DD');
      days.push({
        date: dateStr,
        weekday,
        isOdd: i % 2 === 0, // 用于样式区分
      });
    }
    return days;
  };

  const calendarData = generateCalendarData();
  
  // 根据日历数据和可编辑排班数据，获取每一天的班次状态
  const getDaySchedule = (date) => {
    const scheduleItem = editableSchedule.find(item => dayjs(item.date).format('YYYY-MM-DD') === date);
    return scheduleItem || { morning: 0, afternoon: 0, night: 0 };
  };
  
  return (
    <>
      {contextHolder}
      <ScheduleContainer>
        {/* 医生信息区域 */}
        <DoctorInfoSection>
          <Avatar
            size={80}
            src={userInfo?.head ? getAvatarSrc(userInfo.head) : '/images/default-avatar.png'}
            className="avatar"
          />
          <div className="info">
            <div style={{ marginBottom: '8px' }}>
              <strong>姓名：</strong> {userInfo?.name}
            </div>
            <div style={{ marginBottom: '8px' }}>
              <strong>科室：</strong> {userInfo?.department}
            </div>
            {/* 根据需要添加更多信息 */}
          </div>
        </DoctorInfoSection>

        {/* 排班表格 */}
        {loading ? (
          <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '200px' }}>
            <Spin />
          </div>
        ) : (
          <ScheduleGrid>
            {calendarData.map((day, index) => {
              const schedule = getDaySchedule(day.date);
              return (
                <DayCell key={day.date}>
                  <DayHeader $isOdd={day.isOdd}>
                    {dayjs(day.date).month() + 1}/{dayjs(day.date).date()} {day.weekday}
                  </DayHeader>
                  {/* 显示并可点击修改班次状态 */}
                  <TimeSlot
                    $isOdd={day.isOdd}
                    $active={schedule.morning === 1}
                    onClick={() => handleTimeSlotClick(index, 'morning')}
                  >
                    上午
                  </TimeSlot>
                  <TimeSlot
                    $isOdd={day.isOdd}
                    $active={schedule.afternoon === 1}
                    onClick={() => handleTimeSlotClick(index, 'afternoon')}
                  >
                    下午
                  </TimeSlot>
                  <TimeSlot
                    $isOdd={day.isOdd}
                    $active={schedule.night === 1}
                    onClick={() => handleTimeSlotClick(index, 'night')}
                  >
                    夜班
                  </TimeSlot>
                </DayCell>
              );
            })}
          </ScheduleGrid>
        )}
        
        {/* 底部按钮 */}
        <ButtonContainer>
          <Button type="primary" onClick={handleSubmit} disabled={loading}>
            确认修改排班
          </Button>
        </ButtonContainer>
      </ScheduleContainer>
    </>
  );
};

export default ScheduleManagement;